package ddz.logic.game;

import ch.qos.logback.classic.Logger;
import com.kaka.notice.Message;
import com.kaka.notice.annotation.Handler;
import ddz.constants.Crypto;
import ddz.constants.ErrCode;
import ddz.constants.ErrLevel;
import ddz.constants.OpCode;
import ddz.core.*;
import ddz.db.dao.TableDao;
import ddz.db.service.TableTokenService;
import ddz.net.LogicDataHandler;
import ddz.net.ProtocolMessage;
import ddz.protos.GamePass;
import org.slf4j.LoggerFactory;

/**
 * 过牌
 *
 * @author zkpursuit
 */
@Handler(cmd = OpCode.cmd_pass, type = String.class)
public class PassHandler extends LogicDataHandler {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(PassHandler.class);

    @Override
    public void execute(ProtocolMessage msg) throws Exception {
        GamePass.CsPass reqData = (GamePass.CsPass) msg.getBody();
        TableTokenService optTokenService = this.retrieveProxy(TableTokenService.class);
        TableToken tokenInfo = optTokenService.parseToken(reqData.getToken());
        TableDao deskdao = this.retrieveProxy(TableDao.class);
        Table table = deskdao.getDesk(tokenInfo.getDeskId());
        if (table == null) {
            logger.error("玩家（" + msg.uid() + "）未加入任何房间");
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.no_join_room);
            return;
        }
        Player player = table.getPlayerByUid(msg.uid());
        if (player == null) {
            logger.error("玩家（" + msg.uid() + "）在" + table.getId() + "房间中无对应的数据");
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.data_err);
            return;
        }
        int waitOperateSeatIndex = table.getWaitOperateSeatIndex();
        if (table.getWaitOperateSeatIndex() != player.getSeatIndex()) {
            logger.error("还未轮到玩家（" + msg.uid() + "）在" + table.getId() + "中进行过牌操作");
            sendError(msg.ctx(), opcode(), ErrLevel.WARN, ErrCode.illegal_operation);
            return;
        }
//        if (desk.getStep() != tokenInfo.getStep()) {
//            logger.error("还未轮到玩家（" + msg.uid() + "）在" + desk.getId() + "中进行过牌操作");
//            sendError(msg.ctx(), opcode(), ErrLevel.WARN, ErrCode.illegal_operation);
//            return;
//        }
        if (logger.isInfoEnabled()) {
            logger.info("玩家 [{}：{}] 在 [{}] 房间中过牌", player.getSeatIndex(), msg.uid(), table.getId());
        }
        Player[] players = table.getPlayers();
        table.addOptRecord(new OptRecord(OptType.pass, player.getSeatIndex()));
        this.sendMessage(new Message(OpCode.cmd_show_opts, table));
        byte[] respBytes = GamePass.ScPass.newBuilder()
                .setOpt(OptType.pass.getId())
                .setSeat(waitOperateSeatIndex)
                .build().toByteArray();
        for (Player member : players) {
            this.sendData(member.getUid(), Crypto.isCrypto, opcode(), respBytes);
        }
    }
}
